#!/bin/sh
# Copyright 2010 Guillaume Boudreau
# 
# This file is part of Greyhole.
# 
# Greyhole is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# Greyhole is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Greyhole.  If not, see <http://www.gnu.org/licenses/>.

if [ $# -gt 2 -o $# -lt 1 ]; then
	echo "Usage: $0 directory [files_suffix]"
	exit
fi

if [ $UID -ne 0 ]; then
	echo "You need to be root to execute this command."
	echo "You can use sudo, or become root using the following command: su -"
	exit
fi

DIR=$1

SUFFIX=""
if [ $# -gt 1 ]; then
	SUFFIX="-$2"
fi

for POOL_DIR in `grep storage_pool_directory ${DIR}/greyhole.conf${SUFFIX} | grep -v "[ \t]*#" | awk '{print $3}' | awk -F',' '{print $1}'`; do
	if [ ! -x $POOL_DIR ]; then
		mkdir $POOL_DIR
	fi
	if [ ! -x $POOL_DIR ]; then
		echo "Error: Missing pool directory, and couldn't create: $POOL_DIR"
		exit
	fi
	if [ ! -f $POOL_DIR/.greyhole_uses_this ]; then
		touch $POOL_DIR/.greyhole_uses_this
	fi
done

# Check if Upstart, or init.d scripts, should be used to restart Greyhole and reload Samba
has_daemon=1
if [ -f /etc/rc.d/init.d/functions ]; then
	. /etc/rc.d/init.d/functions
	daemon > /dev/null 2>&1
	has_daemon=$?
fi
man upstart > /dev/null 2>&1
has_upstart=$?

cp /etc/greyhole.conf /etc/greyhole.conf.bak
cp ${DIR}/greyhole.conf${SUFFIX} /etc/greyhole.conf
if [ "$has_daemon" = "0" -a -f /etc/init.d/greyhole ]; then
	# init.d
	/etc/init.d/greyhole restart
else
	
	if [ "$has_upstart" = "0" ]; then
		# Upstart
		restart greyhole
	else
		echo "You should now restart the Greyhole service."
	fi
fi

cp /etc/samba/smb.conf /etc/samba/smb.conf.bak
cp ${DIR}/smb.conf${SUFFIX} /etc/samba/smb.conf
if [ "$has_daemon" = "0" ]; then
	# init.d
	if [ -f /etc/init.d/samba ]; then
		/etc/init.d/samba reload
	elif [ -f /etc/init.d/smb ]; then
		/etc/init.d/smb reload
	else
		echo "You should now restart the Samba service."
	fi
else
	if [ "$has_upstart" = "0" ]; then
		# Upstart
		reload smbd
	else
		echo "You should now restart the Samba service."
	fi
fi
